<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <!--条件查询-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="酒店名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入酒店名称"
              clearable
              size="small"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="queryParams.phone"
              placeholder="请输入手机号"
              clearable
              size="small"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['hotel:base:query']"
            >搜索
            </el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['hotel:base:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['hotel:base:export']"
            >导出
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="userList" border>
          <el-table-column label="名称" align="center" prop="name"/>
          <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true"/>
          <el-table-column label="负责人" align="center" prop="personInCharge" :show-overflow-tooltip="true"/>
          <el-table-column label="组织名称" align="center" prop="deptName" :show-overflow-tooltip="true"/>
          <el-table-column label="授权账号" align="center" prop="account" width="120"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['hotel:base:edit']"
              >修改
              </el-button>
              <el-button
                v-if="scope.row.userId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['hotel:base:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>


    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :before-close="closeDetailDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属组织" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属组织"
                          :disabled="deptid_disabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="酒店名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入酒店名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="personInCharge">
              <el-input v-model="form.personInCharge" placeholder="请输入负责人昵称" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所在位置" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址信息"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="登录账号" prop="account">
              <el-input v-model="form.account" placeholder="请输入登录账号"/>
            </el-form-item>
          </el-col>
          <el-col :span="21">
            <el-form-item label="登陆密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password"/>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="margin-left: 10px">
            <el-button type="primary" @click="updateToken">授 权</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="token" prop="token">
              <el-input v-model="form.token" placeholder="点击更新获取token信息" ref="token" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="过期时间" prop="tokenExpirationTime">
              <el-input v-model="form.tokenExpirationTime" placeholder="点击更新获取token信息以及过期时间" ref="tokenExpirationTime"
                        :disabled="true"
              />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAccountAuthorize,
  accountAuthorizeById,
  addAccountAuthorize,
  putAccountAuthorize,
  delAccountAuthorize,
  getApiTokenAndExpressMessage,
  exportHotel

} from '@/api/system/accountAuthorize.js'
import { getToken } from '@/utils/auth'
import { deptTreeSelect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'User',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      deptid_disabled: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/user/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phone: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '酒店名称不能为空', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '归属组织不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' }
        ],
        personInCharge: [
          { required: false, message: '负责昵称不能为空', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '登陆账号', trigger: 'blur' }
        ],

        token: [
          { required: true, message: 'token不能为空', trigger: 'blur' }
        ],
        tokenExpirationTime: [
          { required: true, message: '过期时间不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: false, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      },
      orgCodeOptions: [{ value: 'zyzn', label: 'zyzn' }, { value: 'gtzn_001', label: 'gtzn_001' }],
      selectedOrgCode: ''
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  //树形结构方法
  created() {
    this.getList()
    this.getTreeselect()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDictDataByType('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.msgname
    })
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listAccountAuthorize(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.selectedOrgCode = data.id
      this.queryParams.deptId = data.id
      this.getList()
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: undefined,
        name: undefined,
        account: undefined,
        password: undefined,
        phone: undefined,
        token: undefined,
        address: undefined,
        tokenExpirationTime: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getTreeselect()

      // 若没有选中组织, 则赋予默认值, 即顶层组织
      if (this.selectedOrgCode === '') {
        this.selectedOrgCode = this.deptOptions[0].id
      }
      this.open = true
      this.title = '酒店信息'
      this.form.deptId = this.selectedOrgCode
      this.deptid_disabled = false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      // 若没有选中组织, 则赋予默认值, 即顶层组织
      if (this.selectedOrgCode === '') {
        this.selectedOrgCode = this.deptOptions[0].id
      }
      const id = row.id || this.ids
      accountAuthorizeById({ id }).then(response => {
        this.form = response.data
        this.open = true
        this.title = '酒店信息'
        this.deptid_disabled = true
      })
    },
    /** 提交按钮 */
    submitForm: function() {

      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            putAccountAuthorize(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addAccountAuthorize(this.form).then(response => {
              if (response.code === 200) {
                console.log(response)
                this.open = false
                this.msgSuccess('新增成功')

                this.getList()
              }
            })
          }
        }
      })
    },

    /**更新用户信息*/
    updateToken() {
      getApiTokenAndExpressMessage(this.form).then(response => {
        if (response.code === 200) {
          this.form.token = response.data.token
          this.form.tokenExpirationTime = response.data.expirationTime
        } else {
          this.msgError('信息错误')
          this.open = false
        }
      })

    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const myIds = []
      myIds.push(row.id)
      const id = myIds || this.ids
      this.$confirm('是否确认删除"' + row.name + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delAccountAuthorize(id)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      console.log('到处成功')
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有酒店数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        console.log('到处成功')
        return exportHotel(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    /**
     * 确认关闭
     */
    closeDetailDialog() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    }

  }
}
</script>
